<template>
  <div class="statorder">
    <a-card title="放单数据" style="width: 100%">
      <div class="statorder_top">
        <a-range-picker
          :ranges="{
            近7天: [moment().startOf('day').subtract(1, 'weeks'), moment()],
            近30天: [moment().startOf('day').subtract(1, 'month'), moment()],
            近两个月: [moment().startOf('day').subtract(2, 'month'), moment()],
          }"
          valueFormat="X"
          :default-value="[moment().startOf('day').subtract(1, 'weeks'), moment()]"
          @change="onChange" />
        <a-button @click="exportToExcel">下载报表</a-button>
      </div>
      <div class="basicdata">
        <div class="data_box">
          <p>放单总数</p>
          <em>{{ all_num.top_order_num }}</em>
        </div>
        <div class="data_box">
          <p>通过数</p>
          <em>{{ all_num.tg_goods_all_num }}</em>
        </div>
        <div class="data_box">
          <p>被拒绝</p>
          <em>{{ all_num.error_all_num }}</em>
        </div>
        <div class="data_box">
          <p>消费点券</p>
          <em>{{ all_num.price }}</em>
        </div>
      </div>
      <div>
        <v-chart :forceFit="true" :height="height" :data="data" :padding="padding">
          <v-tooltip />
          <v-axis />
          <v-legend position="top-center" />
          <v-line position="month*value" color="name" />
          <v-point position="month*value" color="name" :size="4" :v-style="style" :shape="'circle'" />
        </v-chart>
      </div>
      <div>
        <a-table
          :columns="columns"
          :rowKey="goodsList => goodsList.item_id"
          :dataSource="goodsList"
          :loading="loading"
          @change="handleTableChange"
          :pagination="pagination">
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
  import moment from 'moment'
  import {
    exportExcel
  } from '@/assets/js/Export2Excel'

  import {
    getTopUserStatistics,
    getTimeGoodsList
  } from '@/api/stat'
  export default {
    name: 'Statorder',
    data () {
      return {
        data: [],
        height: 400,
        adjust: [{
          type: 'dodge',
          marginRatio: 1 / 32
        }],
        style: {
          stroke: '#fff',
          lineWidth: 1
        },
        padding: [40, 'auto', 20, 'auto'],
        dateFormat: 'YYYY/MM/DD',
        all_num: {
          top_order_num: 8, // 上单数量
          tg_goods_all_num: 1, // 通过总数量
          error_all_num: 0, // 失败数量
          price: 600 // 消费点券总额
        },
        columns: [{
            title: '序号',
            width: 80,
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '商品ID',
            width: 150,
            align: 'center',
            dataIndex: 'item_id',
            scopedSlots: {
              customRender: 'item_id'
            }
          },
          {
            title: '上单时间',
            width: 200,
            align: 'center',
            dataIndex: 'create_at',
            scopedSlots: {
              customRender: 'create_at'
            }
          },
          {
            title: '下架时间',
            align: 'center',
            dataIndex: 'dismount_time',
            scopedSlots: {
              customRender: 'dismount_time'
            }
          },
          {
            title: '下架理由',
            align: 'center',
            dataIndex: 'dismount_reason',
            scopedSlots: {
              customRender: 'dismount_reason'
            }
          },
          {
            title: '商品券后价',
            align: 'center',
            dataIndex: 'goods_after_price',
            scopedSlots: {
              customRender: 'goods_after_price'
            }
          },
          {
            title: '优惠券面值',
            align: 'center',
            dataIndex: 'coupon_discount',
            scopedSlots: {
              customRender: 'coupon_discount'
            }
          },
          {
            title: '消费点券',
            align: 'center',
            dataIndex: 'price',
            scopedSlots: {
              customRender: 'price'
            }
          },
          {
            title: '到期时间',
            align: 'center',
            dataIndex: 'goods_end_time',
            scopedSlots: {
              customRender: 'goods_end_time'
            }
          }

        ],
        pagination: {
          pageSize: 15,
          page: 1
        },
        loading: false,
        goodsList: [],
        startTime: moment().startOf('day').subtract(1, 'weeks').valueOf(),
        endTime: moment().valueOf()
      }
    },

    computed: {

    },
    created () {
      this.getTopUserStatistics(moment().startOf('day').subtract(1, 'weeks').valueOf(), moment().valueOf())
      this.getTimeGoodsList(1, 15, moment().startOf('day').subtract(1, 'weeks').valueOf(), moment().valueOf())
    },
    mounted () {},
    methods: {
      moment,
      exportToExcel () {
        // excel表格数据导出
        require.ensure([], () => {
          const tHeader = ['商品ID', '上单时间', '下架时间', '下架原因', '商品劵后价', '优惠券价格', '消费点券']
          const filterVal = ['item_id', 'create_at', 'dismount_time', 'dismount_reason', 'goods_after_price',
            'coupon_discount', 'price'
          ]
          const list = this.goodsList
          const excelName = '统计数据报表'
          const data = this.formatJson(filterVal, list)
          exportExcel(tHeader, data, excelName)
        })
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      // 上单数据统计 根据时间获取商品信息
      getTimeGoodsList (page, pagesize, starttime, endtime) {
        this.loading = true
        getTimeGoodsList({
            page: page,
            pagesize: pagesize,
            start_time: starttime,
            end_time: endtime
          })
          .then(res => {
            if (res.code === 200) {
              console.log('上单商品返回', res)
              this.goodsList = res.data.data
              const pagination = {
                ...this.pagination
              }
              pagination.total = res.data.count
              this.pagination = pagination
              this.loading = false
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      },

      handleTableChange (pagination, filters) {
        // console.log(pagination)
        const pager = {
          ...this.pagination
        }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch({
          results: pagination.pageSize,
          page: pagination.current,
          ...filters
        })
      },
      fetch (params = {}) {
        // console.log('params:', params)
        this.loading = true
        this.getTimeGoodsList(params.page, 15, this.startTime, this.endTime)
      },
      // 数组提取
      getArrayKey (array, key) {
        var resc = []
        if (array) {
          array.forEach(function (t) {
            resc.push(t[key])
          })
        }
        // 使用: this.getArrayKey(array, "key");
        return resc
      },
      // 获取放单数据
      getTopUserStatistics (startTime, endTime) {
        getTopUserStatistics({
            start_time: startTime,
            end_time: endTime
          })
          .then(res => {
            if (res.code === 200) {
              console.log('放单数据返回', res)
              var time = this.getArrayKey(res.data.list, 'time')
              var tgNum = this.getArrayKey(res.data.list, 'tg_num')
              var bjNum = this.getArrayKey(res.data.list, 'bj_num')
              var todayCount = this.getArrayKey(res.data.list, 'today_count')
              var price = this.getArrayKey(res.data.list, 'price')
              var Name = ['通过数量', '失败数量', '消费点券', '上单数量']
              // console.log('time', time)
              // console.log('Name', Name)
              // console.log('tg_num', tgNum)
              // console.log('bjNum', bjNum)
              // console.log('price', price)
              // console.log('today_count', todayCount)
              const arr = []
              const obj = {}
              const obj2 = {}
              const obj3 = {}
              const obj4 = {}
              for (let i = 0; i < tgNum.length; i++) {
                obj.name = Name[0]
                const key = time[i]
                obj[key] = tgNum[i]
                // console.log('obj', obj)
              }
              arr.push(obj)
              for (let i = 0; i < bjNum.length; i++) {
                obj2.name = Name[1]
                const key = time[i]
                obj2[key] = bjNum[i]
                // console.log('obj2', obj2)
              }
              arr.push(obj2)
              for (let i = 0; i < price.length; i++) {
                obj3.name = Name[2]
                const key = time[i]
                obj3[key] = parseInt(price[i])
                // console.log('obj3', obj3)
              }
              arr.push(obj3)
              for (let i = 0; i < todayCount.length; i++) {
                obj4.name = Name[3]
                const key = time[i]
                obj4[key] = todayCount[i]
                // console.log('obj4', obj4)
              }
              arr.push(obj4)
              console.log('arr', arr)
              const DataSet = require('@antv/data-set')
              const sourceData = arr
              // const sourceData = [{
              //   name: '弟弟',
              //     'Jan.': 18.9,
              //     'Feb.': 28.8,
              //     'Mar.': 39.3,
              //     'Apr.': 81.4,
              //     'May': 47,
              //     'Jun.': 20.3,
              //     'Jul.': 24,
              //     'Aug.': 35.6
              //   }
              // ]
              console.log('sourceData', sourceData)
              const dv = new DataSet.View().source(sourceData)
              dv.transform({
                type: 'fold',
                // fields: ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.'],
                fields: time,
                key: 'month',
                value: 'value'
              })
              this.data = dv.rows
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      },

      onChange (dates, dateStrings) {
        // console.log('From: ', dates[0], ', to: ', dates[1])
        if (dates[0] !== undefined && dates[1] !== undefined) {
          this.startTime = dates[0]
          this.endTime = dates[1]
          this.getTopUserStatistics(dates[0], dates[1])
          this.getTimeGoodsList(1, 15, dates[0], dates[1])
        }
        // console.log('From: ', dateStrings[0], ', to: ', dateStrings[1])
      }
    }
  }
</script>

<style lang='less' scoped>
  .statorder {
    .statorder_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // padding: 10px 0;
      height: 50px;
      background: rgba(239, 243, 245, 1);
      box-sizing: border-box;
      padding: 0 15px;
    }

    .basicdata {
      width: 500px;
      margin: 30px 0 40px;
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 0 10px;

      .data_box {
        p {
          font-size: 14px;
          color: rgba(127, 142, 164, 1);
          line-height: 18px;
          margin-bottom: 15px;
        }

        em {
          font-size: 20px;
          font-family: Arial;
          font-weight: 700;
          color: rgba(51, 60, 72, 1);
          line-height: 18px;
        }
      }
    }
  }
</style>
